import os
import sys
import uvicorn
import edge_tts
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from Response import Response
import librosa
import soundfile as sf
import hashlib

root_path = os.getcwd()
sys.path.append(root_path)
app = FastAPI()

VOICE = "zh-CN-YunjianNeural"
OUTPUT_FILE = "E:\\IIS共享\\Audio\\"


@app.post("/wav")
async def wav(item: dict):
    try:
        text = item['text']
        communicate = edge_tts.Communicate(text, VOICE)
        md5_name = get_md5(text)
        mp3_path = f"{OUTPUT_FILE}{md5_name}.mp3"
        wav_path = f"{OUTPUT_FILE}{md5_name}.wav"
        if not os.path.isfile(wav_path):
            await communicate.save(mp3_path)
            data, sr = librosa.load(mp3_path, sr=16000, mono=True)  # 读取MP3：直接指定16kHz和单通道
            sf.write(wav_path, data, sr, subtype="PCM_16")  # 保存为WAV，指定16位深（PCM_16）
            os.remove(mp3_path)  # 删除临时MP3文件
        return Response().successWithData(md5_name)

    except Exception as e:
        print(e)
        return Response().error("")


def get_md5(string):
    # 创建MD5哈希对象并传入字节数据
    md5_hash = hashlib.md5(string.encode('utf-8'))
    # 返回十六进制哈希字符串
    return md5_hash.hexdigest()


if __name__ == "__main__":
    app.add_middleware(CORSMiddleware,
                       allow_origins=["*"],
                       allow_credentials=True,
                       allow_methods=["*"],
                       allow_headers=["*"], )
    uvicorn.run(app, host='0.0.0.0', port=9533, reload=False)
